package org.mm.web.controller; 


import static org.mm.web.parameter.TherapyParameter.BASE_URL;
import static org.mm.web.parameter.TherapyParameter.COPY_URL;
import static org.mm.web.parameter.TherapyParameter.CREATE_URL;
import static org.mm.web.parameter.TherapyParameter.ENTITY_URL;
import static org.mm.web.parameter.TherapyParameter.LIST_URL;
import static org.mm.web.parameter.TherapyParameter.SEARCH_URL;
import static org.mm.web.parameter.TherapyParameter.SHOW_URL;
import static org.mm.web.parameter.TherapyParameter.SINGLE_LABEL_KEY;
import static org.mm.web.parameter.TherapyParameter.UPDATE_URL;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.mm.frame.jqgrid.JQGridResponse;
import org.mm.frame.jqgrid.JQGridService;
import org.mm.frame.support.SupportHandler;
import org.mm.model.Patient;
import org.mm.model.Therapy;
import org.mm.service.TherapyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@RequestMapping(BASE_URL)
@Controller
public class TherapyController {

	private final Logger log = LoggerFactory.getLogger(TherapyController.class);	

	@Autowired
	private SupportHandler supportHandler;
		
	@Autowired
	private TherapyService therapyService;
	
	@Autowired
	private JQGridService jqgridService;

	
	@RequestMapping(method = RequestMethod.GET)
	public String list() {
		return LIST_URL;
	}
	
	/**
	 * Support pagination for front-end grid 
	 * AJAX call
	 */
	@RequestMapping(value = "/listgrid", method = RequestMethod.GET, produces = "application/json")
	@ResponseBody
	public JQGridResponse<Therapy> listGrid(
			HttpServletRequest request,
			@RequestParam(value = "page", required = false) Integer pageNumber,
			@RequestParam(value = "rows", required = false) Integer rows,
			@RequestParam(value = "sidx", required = false) String sortBy,
			@RequestParam(value = "sord", required = false) String order) {
		log.debug("pageNumber=" + pageNumber);
		log.debug("rows=" + rows);
		log.debug("sortBy=" + sortBy);
		log.debug("order=" + order);
		JQGridResponse<Therapy> gridResponse = new JQGridResponse<Therapy>();
		try {
			Patient patient = (Patient) request.getSession().getAttribute("patient");
			PageRequest pageRequest = jqgridService.prepare(pageNumber, rows, sortBy, order);
			Page<Therapy> page = therapyService.findAllByPage(pageRequest, patient);
			jqgridService.update(page, gridResponse);
		} catch (Exception e) {
			log.error("e", e);
			e.printStackTrace();
			// TODO: handle exception
			//capire come gestire eccezioni: da considerare
			//i parametri jqgrid loadComplete e loadError
		}
		return gridResponse;
	}

	@RequestMapping(params = "create", method = RequestMethod.GET)
    public String createForm(Model uiModel) {
		Therapy therapy = new Therapy();
        uiModel.addAttribute("therapy", therapy);
        return CREATE_URL;
    }
	
	@RequestMapping(params = "create", method = RequestMethod.POST)
    public String create(@Valid Therapy therapy, BindingResult bindingResult, Model uiModel, 
    		HttpServletRequest request, Locale locale) {
		String redirect = "";		
        if (bindingResult.hasErrors()) {
			uiModel.addAttribute("message", supportHandler.retrieveCreateErrorMessage(SINGLE_LABEL_KEY, locale));
			uiModel.addAttribute("therapy", therapy);
            redirect = CREATE_URL;
        } else {        
        	uiModel.asMap().clear();
        	try {
				therapyService.save(therapy);
				uiModel.addAttribute("message", supportHandler.retrieveCreateSuccessMessage(SINGLE_LABEL_KEY, locale));
				redirect = supportHandler.prepareEntityUrl(ENTITY_URL, therapy.getTherapyId(), request);
			} catch (Exception e) {
				log.error("e", e);
				uiModel.addAttribute("message", supportHandler.retrieveGenericErrorMessage(e.getMessage()));
				uiModel.addAttribute("therapy", therapy);
				redirect = CREATE_URL;
			}
        }        
        return redirect;
    }	

	@RequestMapping(value = "/{id}", params = "update", method = RequestMethod.GET)
    public String updateForm(@PathVariable("therapyId") Long id, Model uiModel) {
		try {
			Therapy therapy = therapyService.findById(id);
			uiModel.addAttribute("therapy", therapy);
		} catch (Exception e) {
			log.error("e", e);
			uiModel.addAttribute("message", supportHandler.retrieveGenericErrorMessage(e.getMessage()));
		}
        return UPDATE_URL;
	}

	@RequestMapping(value = "/{id}", params = "update", method = RequestMethod.POST)
    public String update(@Valid Therapy therapy, BindingResult bindingResult, Model uiModel,
    		HttpServletRequest request,  Locale locale) {
        try {
			therapyService.save(therapy);
		} catch (Exception e) {
			log.error("e", e);
			uiModel.addAttribute("message", supportHandler.retrieveGenericErrorMessage(e.getMessage()));
		}
        return supportHandler.prepareEntityUrl(ENTITY_URL, therapy.getTherapyId(), request);
    }
	
	@RequestMapping(value = "/{id}", params = "copy", method = RequestMethod.GET)
    public String copyForm(@PathVariable("therapyId") Long id, Model uiModel) {
		try {
			Therapy therapy = therapyService.findById(id);
			therapy.setTherapyId(null);
			uiModel.addAttribute("therapy", therapy);
		} catch (Exception e) {
			log.error("e", e);
			uiModel.addAttribute("message", supportHandler.retrieveGenericErrorMessage(e.getMessage()));
		}
        return COPY_URL;
	}
	
	@RequestMapping(value = "/{id}", params = "copy", method = RequestMethod.POST)
    public String copy(@Valid Therapy therapy, BindingResult bindingResult, Model uiModel, 
    		HttpServletRequest request, Locale locale) {
		return create(therapy, bindingResult, uiModel, request, locale);
	}
	
	
	@RequestMapping(params = "search", method = RequestMethod.GET)
    public String searchForm(Model uiModel) {
		Therapy therapy = new Therapy();
        uiModel.addAttribute("therapy", therapy);
        return SEARCH_URL;
    }
	
	@RequestMapping(params = "search", method = RequestMethod.POST)
    public String search(@Valid Therapy therapy, BindingResult bindingResult, Model uiModel, 
    		HttpServletRequest request,  Locale locale) {		
/*		try {
			//therapyService.search(therapy);
			JQGridResponse<Therapy> gridResponse = new JQGridResponse<Therapy>();
			PageRequest pageRequest = jqgridService.prepare(1, 10, null, null);
			Page<Therapy> page = therapyService.findOneByPage(therapy.getId(), pageRequest);
			jqgridService.update(page, gridResponse);
			
			for (Therapy t : gridResponse.getRows()) {
				log.debug(t.toString());
			}
			log.debug("end");

		} catch (Exception e) {
			log.error("e", e);
			//uiModel.addAttribute("message", supportHandler.retrieveGenericErrorMessage(e.getMessage()));
		}*/
		return LIST_URL; 
		
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String show(@PathVariable("id") Long id, Model uiModel) {
		try {
			Therapy therapy = therapyService.findById(id);
			uiModel.addAttribute("therapy", therapy);
		} catch (Exception e) {
			log.error("e", e);
			uiModel.addAttribute("message", supportHandler.retrieveGenericErrorMessage(e.getMessage()));
		}
        return SHOW_URL;
    }
	
	
	@RequestMapping(value = "/{id}", params = "delete", method = RequestMethod.GET)
	public String delete(@PathVariable("id") Long id, Model uiModel, Locale locale) {
        try {
        	Therapy therapy = therapyService.findById(id);
			therapyService.delete(therapy);
		} catch (Exception e) {
			log.error("e", e);
			uiModel.addAttribute("message", supportHandler.retrieveGenericErrorMessage(e.getMessage()));
		}
        return LIST_URL;
	}
}
